<?php
namespace App\Logics;

use Illuminate\Support\Facades\Storage;
use Illuminate\Http\Request;

use App\Libs\Vendor\AliPaySdk\aop\AopClient;
use App\Libs\Vendor\AliPaySdk\aop\request\AlipaySecurityRiskCustomerriskQueryRequest;
class BaseLogic
{
    public function __construct()
    {
    }

    protected final function tree($arr, $pid = 0, $level = 0)
    {
        static $data = array();
        foreach ($arr as $k => $v) {
            if ($v['pid'] == $pid) {
                $arr[$k]['level'] = $level;
                $arr[$k]['level_str'] = str_repeat('|&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;', $level);
                $data[] = $arr[$k];
                unset($arr[$k]);
                $this->tree($arr, $v['cate_id'], $level + 1);
            }
        }
        return $data;
    }

    //删除图片
    public function deleteImg($path){
        return  Storage::disk('admin')->delete($path);
    }

    //本地图片上传
    public function localUploadImgs(Request $request,$filename='img',$path='',$saveFileName='')
    {
        $filename=$filename?$filename:'img';
        if(!$request->hasFile($filename)){
            return  ['status'=>0,'data'=>'请上传图片'];
        }

        $file = $request->file($filename);

        $allow_ext=['jpg','png','jpeg','gif'];
        if ($file->isValid()) {
            $originalName = $file->getClientOriginalName(); //原文件名
            $ext = $file->getClientOriginalExtension();  //扩展名
            if(!in_array($ext,$allow_ext)){
                return ['status'=>0,'data'=>'请上传图片类型'];
            }
            $type = $file->getClientMimeType();  //mime类型
            $realPath = $file->getRealPath();
            $filename=date('Ymd').uniqid() . '.' . $ext;
            $filename =$saveFileName?$saveFileName.'.'.$ext: $filename;
            if($path){
                $path=trim($path,'/');
                $filename=$path."/".$filename;
            }

            $bool = Storage::disk('admin')->put($filename, file_get_contents($realPath));

            if($bool){
                return ['status'=>1,'data'=>$filename];
            }
            return   ['status'=>0,'data'=>'上传失败'];
        }
        return ['status'=>0,'data'=>'上传失败'];;
    }

    //上传图片到图片服务器
    public  function curlUploadImg(string  $file,string $path){
        if(empty($file)) return false;

        $file='storage/'.$file;
        $minetype = 'image/jpeg';
        $curl_file = curl_file_create($file, $minetype);
        $url =  config('sys.upload_url');
        $post_data = ['img' => $curl_file,'savePath'=>$path];
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        if(strpos($url,'https')!==false){
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书和hosts
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        }
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        $output = curl_exec($ch);
        curl_close($ch);


        if(empty($output)) return false;
        return  json_decode($output,true);
    }

    //图片上传
    public function uploadImg(Request $request,$filename='img',$path='',$saveFileName='')
    {
        $filename=$filename?$filename:'img';
        if(!$request->hasFile($filename)){
            return  ['status'=>0,'data'=>'请上传图片'];
        }
        $file = $request->file($filename);
        $allow_ext=['jpg','png','jpeg','gif'];
        if ($file->isValid()) {
            $originalName = $file->getClientOriginalName(); //原文件名
            $ext = $file->getClientOriginalExtension();  //扩展名
            if(!in_array($ext,$allow_ext)){
                return ['status'=>0,'data'=>'请上传图片类型'];
            }
            $type = $file->getClientMimeType();  //mime类型
            $realPath = $file->getRealPath();
            $filename=date('Ymd').uniqid() . '.' . $ext;
            $filename =$saveFileName?$saveFileName.'.'.$ext: $filename;
            if($path){
                $path=trim($path,'/');
                $filename=$path."/".$filename;
            }
            $bool = Storage::disk('admin')->put($filename, file_get_contents($realPath));
            if($bool){
                //上传远程图片服务器
                $res=$this->curlUploadImg($filename,$path);
                if(empty($res) || !is_array($res)){
                    return error('远程上传失败');
                }
                //删除本地图片
                $this->deleteImg($filename);
                if(isset($res['status']) && $res['status']==1001){
                    return ['status'=>1,'data'=>$res['data']['imgUrl']];
                }
                return ['status'=>0,'data'=>$res['msg']];
            }
            return   ['status'=>0,'data'=>'上传失败'];
        }
        return ['status'=>0,'data'=>'上传失败'];;
    }


    //分页数码处理
    protected final function page($totalPage, $page)
    {
        $page = (int)$page;
        if ($page < 1) $page = 1;
        if ($page > $totalPage) $page = $totalPage;
        $list = [];
        if ($page - 2 < 5) {
            $list = [1, 2, 3, 4, 5, 6, 7, 8, 9, $totalPage - 1, $totalPage];
        }
        if ($page - 2 >= 5) {
            $list = [1, 2, $page - 3, $page - 2, $page - 1, $page, $page + 1, $page + 2, $page + 3, $totalPage - 1, $totalPage];
        }
        if ($totalPage - 1 - $page < 5) {
            $list = [1, 2, $totalPage - 8, $totalPage - 7, $totalPage - 6, $totalPage - 5, $totalPage - 4, $totalPage - 3, $totalPage - 2, $totalPage - 1, $totalPage];
        }
        $list = array_unique($list);
        sort($list);
        $lists = [];
        foreach ($list as $k => $v) {
            if ($v >= 1 && $v <= $totalPage) $lists[] = $v;
        }

        $page = [];
        foreach ($lists as $k => $v) {
            $page[] = $v;
            if (isset($lists[$k + 1]) && (($lists[$k] + 1) < $lists[$k + 1])) {
                $page[] = '...';
            }
        }
        return $page;
    }

    //获取先享后付的测评结果
    protected function get_xxhf($data){

        if(!isset($data['phone']) || !isset($data['idcard']) || !isset($data['amount']) || !isset($data['zm_user_id'])) return false;
        $aop = new AopClient();
        $pid=$aop->pid;
        $request = new AlipaySecurityRiskCustomerriskQueryRequest();
        $data=[
            'risk_type'=>'riskinfo_nsf_common',
            'mobile_no'=>$data['phone']??'null',
            'cert_no'=>$data['idcard']??'null',
            'service'=>'nsf',
            'pid'=>$pid,
            'sales_amount'=>$data['amount'],
            'user_id'=>$data['zm_user_id']??'null'
        ];
        $request->setBizContent(json_encode($data));
        $result = $aop->execute ( $request);

        if(empty($result['alipay_security_risk_customerrisk_query_response'])){
            return false;
        }
        if($result['alipay_security_risk_customerrisk_query_response']['code']!=10000) {
            return false;
        }
        $risk_result=json_decode($result['alipay_security_risk_customerrisk_query_response']['risk_result'],true);
        $risk_result_desc=json_decode($result['alipay_security_risk_customerrisk_query_response']['risk_result_desc'],true);
        if(isset($risk_result['errorCode']))  return false;
        $data=[
            'rank0'=>'提供信息不足或提供参数信息有误',
            'rank1'=>'用户拒付风险指数：低',
            'rank2'=>'用户拒付风险指数：中',
            'rank3'=>'用户拒付风险指数：高'
        ];
        return $data[array_keys($risk_result_desc)[0]]??'未知错误';
    }


}